import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import prisma from '@/lib/db';

export async function PATCH(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const { language } = data;
    
    if (!language) {
      return NextResponse.json(
        { error: '缺少必要参数' },
        { status: 400 }
      );
    }

    // 验证语言值
    const validLanguages = ['zh_CN', 'en_US'];
    if (!validLanguages.includes(language)) {
      return NextResponse.json(
        { error: '无效的语言值' },
        { status: 400 }
      );
    }

    // 更新用户语言设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: {
        language
      },
      create: {
        userId,
        language,
        theme: 'system',
        themeColor: 'blue',
        emailNotifications: true,
        pushNotifications: true,
        weeklyDigest: true,
      }
    });

    return NextResponse.json({
      success: true,
      data: updatedSettings,
      message: '语言设置已更新'
    });
  } catch (error) {
    console.error('更新语言设置失败:', error);
    return NextResponse.json(
      { error: '更新语言设置失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await auth();
    
    // 检查用户是否已登录
    if (!session?.user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const userId = session.user.id;
    const data = await request.json();
    
    // 验证数据
    const { language } = data;
    
    if (!language) {
      return NextResponse.json(
        { error: '缺少必要参数' },
        { status: 400 }
      );
    }

    // 验证语言值
    const validLanguages = ['zh_CN', 'en_US'];
    if (!validLanguages.includes(language)) {
      return NextResponse.json(
        { error: '无效的语言值' },
        { status: 400 }
      );
    }

    // 更新用户语言设置
    const updatedSettings = await prisma.userSettings.upsert({
      where: { userId },
      update: {
        language
      },
      create: {
        userId,
        language,
        theme: 'system',
        themeColor: 'blue',
        emailNotifications: true,
        pushNotifications: true,
        weeklyDigest: true,
      }
    });

    return NextResponse.json(updatedSettings);
  } catch (error) {
    console.error('更新语言设置失败:', error);
    return NextResponse.json(
      { error: '更新语言设置失败' },
      { status: 500 }
    );
  }
} 